package be.ac.ua.bank;

import java.rmi.RMISecurityManager;
import java.rmi.Remote;

import be.ac.ua.codebase.BankAccountInterface;
import be.ac.ua.codebase.BankInterface;

import net.jini.config.Configuration;
import net.jini.config.ConfigurationProvider;
import net.jini.core.entry.Entry;
import net.jini.core.lookup.ServiceID;
import net.jini.discovery.LookupDiscovery;
import net.jini.export.Exporter;
import net.jini.jeri.BasicILFactory;
import net.jini.jeri.BasicJeriExporter;
import net.jini.jeri.tcp.TcpServerEndpoint;
import net.jini.lease.LeaseRenewalManager;
import net.jini.lookup.JoinManager;
import net.jini.lookup.ServiceIDListener;
import net.jini.lookup.entry.Name;

public class BankServer implements ServiceIDListener {
	private Remote fProxy;
	private BankImplementation fImplementation;
	private JoinManager fJoinManager;
	
	public static void main(String[] args) {
		System.setSecurityManager(new RMISecurityManager());
		
		try {
			new BankServer();
			
			while(true){}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public BankServer() throws Exception {
		fImplementation = new BankImplementation();
		Exporter exporter = new BasicJeriExporter(TcpServerEndpoint.getInstance(0), new BasicILFactory());
		fProxy = exporter.export((BankInterface)fImplementation); 
		
		String[] groups = new String[] {"NDFLEXTRADE"};
		LookupDiscovery discoveryManager = new LookupDiscovery(groups);
		Entry[] attributes = new Entry[] {new Name("Bank")}; 
		fJoinManager = new JoinManager(fProxy, attributes, this, discoveryManager, new LeaseRenewalManager());
	}

	public void serviceIDNotify(ServiceID serviceID) {
		System.out.println("[BANK SERVER] Server got ID " + serviceID.toString());
		Entry[] attributes = new Entry[] {new Name(serviceID.toString())}; 
		fJoinManager.setAttributes(attributes);
		fImplementation.setName(serviceID.toString());
	}

}
